package fem2.observer;

import fem2.Element;
import fem2.Load;
import fem2.Model;
import fem2.Observer;

/**
 * TODO
 * 
 * @author hbui
 * 
 */
public class DeactivationUtility implements Observer {

	private Model m;

	private int fromDeac, toDeac;
	private int fromReac, toReac;

	private int deltaDeac, deltaReac;

	public DeactivationUtility(Model m, int fromDeac, int deltaDeac, int fromReac, int deltaReac) {
		this.m = m;

		this.fromDeac = fromDeac;
		this.toDeac = fromDeac;
		this.fromReac = fromReac;
		this.toReac = fromReac;

		this.deltaDeac = deltaDeac;
		this.deltaReac = deltaReac;
	}

	@Override
	public void fireStarted() {
		/*
		 * deactivate elements
		 */
		for (int i = 0; i < m.countElements(); i++) {
			Element e = m.getElement(i);
			int activationLevel = e.getActivationLevel();
			if (activationLevel < 0) {
				e.deactivate();
			}
		}

		/*
		 * deactivate loads
		 */
		for (int i = 0; i < m.countLoads(); i++) {
			Load l = m.getLoad(i);
			int activationLevel = l.getActivationLevel();
			if (activationLevel < 0) {
				l.deactivate();
			}
		}
	}

	@Override
	public void fireTimeStepStarted() {
		/*
		 * deactivate/reactivate elements
		 */
		for (int i = 0; i < m.countElements(); i++) {
			Element e = m.getElement(i);
			int activationLevel = e.getActivationLevel();
			if (activationLevel >= fromDeac && activationLevel < toDeac) {
				e.deactivate();
			}
			if (activationLevel >= fromReac && activationLevel < toReac) {
				e.reactivate();
			}
		}

		/*
		 * deactivate/reactivate loads
		 */
		for (int i = 0; i < m.countLoads(); i++) {
			Load l = m.getLoad(i);
			int activationLevel = l.getActivationLevel();
			if (activationLevel >= fromDeac && activationLevel < toDeac) {
				l.deactivate();
			}
			if (activationLevel >= fromReac && activationLevel < toReac) {
				l.reactivate();
			}
		}
	}

	@Override
	public void fireIterationStarted() {
		/*
		 * do nothing
		 */
	}

	@Override
	public void fireIterationFinished() {
		/*
		 * do nothing
		 */
	}

	@Override
	public void fireTimeStepFinished() {
		/*
		 * update deactivation/reactivation range
		 */
		toDeac += deltaDeac;
		toReac += deltaReac;
	}

	@Override
	public void fireFinished() {
		/*
		 * do nothing
		 */
	}

}
